//package com.tansun.easycare.rule.ruleproj.web;
//
//import java.io.File;
//import java.io.InputStream;
//import java.io.PrintWriter;
//import java.io.Serializable;
//import java.lang.reflect.Field;
//import java.text.SimpleDateFormat;
//import java.util.ArrayList;
//import java.util.Date;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//
//import org.apache.commons.io.FileUtils;
//import org.apache.commons.io.IOUtils;
//import org.apache.commons.lang3.exception.ExceptionUtils;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.context.ApplicationContextException;
//import org.springframework.stereotype.Controller;
//import org.springframework.ui.ModelMap;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.ResponseBody;
//
//import com.alibaba.druid.util.StringUtils;
//import com.alibaba.fastjson.JSON;
//import com.tansun.easycare.modules.sys.entity.User;
//import com.tansun.easycare.modules.sys.utils.UserUtils;
//import com.tansun.easycare.rule.common.JsonMessage;
//import com.tansun.easycare.rule.common.RuleBaseController;
//import com.tansun.easycare.rule.ruleproj.entity.RuleProject;
//import com.tansun.easycare.rule.ruleproj.service.RuleProjectService;
//
///**
// * 规则项目管理Action
// * @author Lph
// *
// */
//@Controller
//@RequestMapping(value = "/ruleProject")
//public class RuleProjectManageAction extends RuleBaseController {
//	private static final Logger logger = LoggerFactory.getLogger(RuleProjectManageAction.class);
//
//	@Autowired
//	private RuleProjectService ruleProjectService; 
//	/**
//	 * 当前规则项目页面
//	 * modify date:20160301  by WY
//	 * add for:根据当前用户进入规则页面调整
//	 * @param projectCode
//	 * @param map
//	 * @param request
//	 * @return
//	 * @throws Exception
//	 */
//	@RequestMapping("ruleConsole")
//	public String ruleConsole(ModelMap map,HttpServletRequest request) throws Exception
//	{
//		User user = this.getCurrUser();
//		List<RuleProject> ruleList = new ArrayList<RuleProject>();
//		if("administrator".equals(user.getLoginName())){
//			String path = RuleProject.HOMEPATH+"/ruleProject.xml";
//			ModelItemCollection<RuleProject> collection = (ModelItemCollection<RuleProject>) JavaUnmarshaller.xml2Bom(path, ModelItemCollection.class);
//			if(collection!=null) 
//				ruleList = collection.getModelItemList();
//		}else{
//			ruleList = this.ruleProjectService.getUsersProject();
//		}
//		
//		String projectCode = request.getParameter("projectCode");
//		if(ruleList.size()>=1){
//			//直接进入规则项目页面 呈现所有的第一个规则项目的内容
//			if(projectCode==null){
//				projectCode = ruleList.get(0).getProjectCode();
//			}
//			projectCode = new String(projectCode.getBytes("ISO8859-1"),"UTF-8");
//			RuleProject rule = ruleProjectService.getRuleProjectByCode(projectCode);
//			map.put("rule", rule);
//			super.setCurrProjectCode(projectCode);
//			map.put("ruleList", ruleList);
//			return "ruleproject/ruleManageItem";
//		}else{
//			//提示没有授权的项目
//			return "ruleproject/noruleProj";
//		}
//	} 
//	/**
//	 * 跳转至规则项目列表
//	 * @param condition 搜索信息收集模型(暂不用)
//	 * @param map
//	 * @return
//	 * @throws Exception
//	 */
//	@RequestMapping("ruleList")
//	public String ruleList(HttpServletRequest request,RuleProject condition,ModelMap map) throws Exception
//	{
//		try{
//			/***这段暂时保留，转换之前的xml***/
//			String savePath = RuleProject.HOMEPATH+"/ruleProject.xml";
//			List<RuleProject> ruleList = XmlHelper.objectXmlDecoder(savePath);
//			ModelItemCollection<RuleProject> collection = new ModelItemCollection<RuleProject>(ruleList);
//			JavaUnmarshaller.bom2Xml(savePath, collection, ModelItemCollection.class);
//			for(RuleProject rule:ruleList){
//				String userPath = RuleProject.HOMEPATH+"/"+rule.getProjectCode()+"/userAuthority.xml";
//				List<UserAuthority> userList = XmlHelper.objectXmlDecoder(userPath);
//				ModelItemCollection<UserAuthority> userCollection = new ModelItemCollection<UserAuthority>(userList);
//				JavaUnmarshaller.bom2Xml(userPath, userCollection, ModelItemCollection.class);
//			}
//			
//		}catch(Exception e){
//			return "ruleproject/ruleManage";
//		}
//		return "ruleproject/ruleManage";
//	} 
//	/**
//	 * 保存规则项目
//	 * @param projectInfo 规则项目信息
//	 * @param userAuthority 规则项目对应的用户权限信息
//	 * @return 是否保存成功，包含异常信息
//	 */
//	@RequestMapping("saveRuleProject")
//	public @ResponseBody JsonMessage saveRuleProject(String projectInfo,String userAuthority,HttpServletRequest request){
//		JsonMessage ret = new JsonMessage();
//		ret.setMessage("保存成功");
//		try{
//			RuleProject rule = JSON.parseObject(projectInfo, RuleProject.class);
//			saveRule(rule);
//			List<UserAuthority> usersList = JSON.parseArray(userAuthority, UserAuthority.class);  
//			if(usersList!=null && usersList.size()>0)
//			{
//				String savePath = RuleProject.HOMEPATH+"/"+rule.getProjectCode()+"/userAuthority.xml";
//				ModelItemCollection<UserAuthority> collection = new ModelItemCollection<UserAuthority>(usersList);
//				JavaUnmarshaller.bom2Xml(savePath, collection, ModelItemCollection.class);
////				XmlHelper.objectXmlEncoder(usersList, savePath);
//				createPath(usersList.get(0),rule);
//			}
//		}catch(Exception e){
//			logger.debug(ExceptionUtils.getStackTrace(e));
//			ret.setResult(false);
//			if(e instanceof ApplicationContextException){
//				ret.setMessage(e.getMessage());
//			}else{
//				ret.setMessage("数据保存失败，请查看日志");
//			}
//		}
//		return ret;
//	}
//	/**
//	 * 修改规则 项目状态
//	 * @param projectId 规则项目ID
//	 * @param status 修改的状态
//	 */
//	@RequestMapping("ruleStatusChange")
//	public @ResponseBody JsonMessage ruleStatusChange(String projectId,String status,HttpServletRequest request) throws Exception{
//		JsonMessage ret = new JsonMessage();
//		try {
//			RuleProject rule = new RuleProject();
//			rule.setProjectId(projectId);
//			rule.setStatus(status);
//			saveRule(rule);
//		} catch (Exception e) {
//			logger.debug(ExceptionUtils.getStackTrace(e));
//			ret.setResult(false);
//			ret.setMessage("状态修改失败，请查看日志");
//		}
//		return ret;
//	}
//	/**
//	 * 规则项目详情
//	 * @param projectCode 规则项目编码
//	 * @param request
//	 * @return 规则项目信息
//	 * @throws Exception
//	 */
//	@RequestMapping("ruleDetail")
//	public @ResponseBody JsonMessage ruleDetail(String projectCode,HttpServletRequest request) throws Exception{
//		JsonMessage ret = new JsonMessage();
//		try{
//			String savePath = RuleProject.HOMEPATH+"/"+projectCode+"/userAuthority.xml";
//			ModelItemCollection<UserAuthority> collection = (ModelItemCollection<UserAuthority>) JavaUnmarshaller.xml2Bom(savePath, ModelItemCollection.class);
//			if(collection==null)
//				collection = new ModelItemCollection<UserAuthority>();
//			ret.setData((Serializable) collection.getModelItemList());
//		}
//		catch(Exception e)
//		{
//			logger.debug(ExceptionUtils.getStackTrace(e));
//			
//			ret.setResult(false);
//			ret.setMessage("规则信息获取失败，请查看日志");
//		}
//		return ret;
//	}
//	/**
//	 * 文件夹中是否存在模型
//	 * @param projectCode 规则项目编码
//	 * @param parameterCode 规则模型编码
//	 * @param request
//	 * @return 模型中是否已经存在规则文件
//	 * @throws Exception
//	 */
//	@RequestMapping("isExistsModelFile")
//	public @ResponseBody JsonMessage isExistsModelFile(String projectCode,String parameterCode,HttpServletRequest request) throws Exception{
//		JsonMessage ret = new JsonMessage();
//		try {
//			String baseRoot = RuleProject.HOMEPATH + "/" + projectCode + "/" + parameterCode;
//			File fileFolder = new File(baseRoot);
//			File list[] = fileFolder.listFiles();
//			if (list != null && list.length > 0) {
//				throw new ApplicationContextException("已经存在模型文件，无法清除");
//			}
//		} catch (Exception e) {
//			logger.debug(ExceptionUtils.getStackTrace(e));
//			ret.setResult(false);
//			ret.setMessage(e.getMessage());
//		}
//		return ret;
//	}
//	/**
//	 * 保存规则信息
//	 * @param rule 规则项目信息
//	 * @throws Exception
//	 */
//	private void saveRule(RuleProject rule) throws Exception
//	{
//		String savePath = RuleProject.HOMEPATH+"/ruleProject.xml";
//		ModelItemCollection<RuleProject> collection = (ModelItemCollection<RuleProject>) JavaUnmarshaller.xml2Bom(savePath, ModelItemCollection.class);
//		List<RuleProject> ruleList = new ArrayList<RuleProject>();
//		if(collection==null){
//			collection = new ModelItemCollection<RuleProject>();
//		}else{
//			ruleList = collection.getModelItemList();
//		}
//		if(exists(ruleList, rule)){
//			throw new ApplicationContextException("此项目名称或项目编码已经存在，请修改");
//		}
//		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
//		if(StringUtils.isEmpty(rule.getProjectId()))
//		{
//			SimpleDateFormat id = new SimpleDateFormat("yyyyMMddHHmmss");
//			rule.setProjectId(id.format(new Date()));
//			rule.setStatus("1");
//			rule.setCreatedBy(this.getCurrUser().getLoginName());
//			rule.setCreatedOn(df.format(new Date()));
//			ruleList.add(rule);
//		}
//		else
//		{
//			for(RuleProject item:ruleList)
//			{
//				if(item.getProjectId().equals(rule.getProjectId()))
//				{
//					item.setModifiedBy(this.getCurrUser().getLoginName());
//					item.setModifiedOn(df.format(new Date()));
//					item.InitModifiedContent(rule);
//				}
//			}
//		}
//		collection.setModelItemList(ruleList);
//		JavaUnmarshaller.bom2Xml(savePath, collection, ModelItemCollection.class);
////		XmlHelper.objectXmlEncoder(ruleList, savePath);
//	}
//	/**
//	 * 是否存在同名，或者相同编号的规则项目
//	 * @param ruleList 规则项目列表
//	 * @param rule 要检查的规则项目
//	 * @return
//	 */
//	private boolean exists(List<RuleProject> ruleList,RuleProject rule)
//	{
//		for(RuleProject item:ruleList)
//		{
//			if(StringUtils.isEmpty(rule.getProjectId()))
//			{
//				if(item.getProjectCode().equals(rule.getProjectCode()) || item.getProjectName().equals(rule.getProjectName()))
//				{
//					return true;
//				}
//			}
//			else
//			{
//				if((item.getProjectCode().equals(rule.getProjectCode()) || item.getProjectName().equals(rule.getProjectName())) 
//					&& !item.getProjectId().equals(rule.getProjectId()))
//				{
//					return true;
//				}
//			}
//		}
//		return false;
//	}
//	/**
//	 * 对规则项目所对应的用户，建立对应的文件夹
//	 * @param user
//	 * @param rule
//	 * @throws Exception
//	 */
//	private void createPath(UserAuthority user,RuleProject rule) throws Exception
//	{
//		String basePath = RuleProject.HOMEPATH + "/"+rule.getProjectCode();
//		Class cls = user.getClass();
//		java.lang.reflect.Field[] flds = cls.getDeclaredFields();
//	    for ( int i = 0; i < flds.length; i++ )  
//	    {  
//	    	Field f = flds[i];  
//	        f.setAccessible(true); //设置些属性是可以访问的  
//	        Object val = f.get(user);//得到此属性的值 
//	        if(f.getName().equals("serialVersionUID")
//	        		|| f.getName().equals("userCode")
//	        		|| f.getName().equals("userName")
//	        		|| f.getName().equals("projectCode"))
//	        {
//	        	continue;
//	        }
//			String filePath = basePath+"/"+f.getName();
//			File file = new File(filePath);
//	        if(val == null)
//	        {
//	        	file.delete();
//	        	continue;
//	        }
//			if(!file.exists())
//			{
//				file.mkdirs();
//			}
//	    }
//	    
//	    //添加规则集用户自定义函数配置文件 by WY
//	    String userFunPath = RuleProject.HOMEPATH + "/"+rule.getProjectCode()+"/userFun";
//	    File userfile = new File(userFunPath);
//	    if(!userfile.exists())
//		{
//	    	userfile.mkdirs();
//		}
//	    InputStream is = RuleProjectManageAction.class.getResourceAsStream("/config/userjfun.xml");
//	    String userfunxml = IOUtils.toString(is,"UTF-8");
//	    FileUtils.writeStringToFile(new File(userFunPath+"/userFun.xml"),userfunxml,"UTF-8");
//	    if(is!=null){
//	    	is.close();
//	    }
//	}
//	
//	/**
//	 * 获取所有用户
//	 * author WY
//	 * @param request
//	 * @param response
//	 * @throws Exception
//	 */
//	@RequestMapping("zuserData")
//	public void ruleSetEditJsonData(HttpServletRequest request, HttpServletResponse response) throws Exception
//	{
//		List<User> users = UserUtils.getUserListByRole("");
//		List<Map<String, Object>> listZuser = new ArrayList<Map<String, Object>>();
//		for (User sysUser : users) {
//			Map<String, Object> map = new HashMap<String, Object>();
//			map.put("id", sysUser.getLoginName());
//			map.put("name", sysUser.getName());
//			listZuser.add(map);
//			
//		}
//		String jsondata = JSON.toJSONString(listZuser);
//		
//		response.setContentType("application/json;charset=UTF-8");
//		PrintWriter writer = response.getWriter();
//		writer.print(jsondata);
//		writer.flush();
//	}
//	/**
//	 * 获取当前用户的权限
//	 * author WY
//	 * @param request
//	 * @param response
//	 * @throws Exception
//	 */
//	@RequestMapping("getUserAuthority")
//	public void getUserAuthority(HttpServletRequest request, HttpServletResponse response) throws Exception
//	{
//		String jsondata = null;
//		
//		User user = UserUtils.getUser();
//		if("administrator".equals(user.getLoginName())){
//			jsondata="{\"userType\":\"administrator\"}";
//		}else{
//			UserAuthority ua =  this.ruleProjectService.getUsersUserAuthority();
//			jsondata = JSON.toJSONString(ua);
//			jsondata = "{\"userType\":\"user\",\"authData\":"+jsondata+"}";
//			
//		}
//		
//		response.setContentType("application/json;charset=UTF-8");
//		PrintWriter writer = response.getWriter();
//		writer.print(jsondata);
//		writer.flush();
//	}
//
//	/**
//	 * 规则引擎系统帮助
//	 * modify by linmin on 20160808
//	 * @param request
//	 * @param response
//	 * @return
//	 * @throws Exception 
//	 */
//	@RequestMapping("ruleHelper")
//	public String ruleHelper(HttpServletRequest request, HttpServletResponse response) throws Exception {
//		return "ruleHelper/operationManual";
//	}
//}
